// 实现UI交互逻辑，如添加、查看、删除书签。
// 获取所有书签
function getTree() {
  return new Promise((resolve, reject) => {
    chrome.bookmarks.getTree((bookmarkTreeNodes) => {
      resolve(bookmarkTreeNodes);
    });
  });
}

function traverse(bookmarkTreeNodes) {
  console.log(bookmarkTreeNodes);
  // 迭代遍历书签树，利用 Map 找出重复书签
  let map = new Map();
  let map2 = new Map(); // key 为网页标题，找出网页标题一样的书签
  let queue = [bookmarkTreeNodes[0]];

  let allBookmarks = new Set(); // 所有书签
  let repeatBookmarks = Object.create(null); // 记录重复的书签
  let repeatBookmarks2 = Object.create(null); // 记录重复的书签(网页标题一样的书签)
  let category = Object.create(null); // 记录书签分类
  let emptyCategory = Object.create(null); // 记录空分类

  while (queue.length) {
    let node = queue.shift();
    // 目录
    if (node.children) {
      queue = queue.concat(node.children);
      category[node.id] = node;
      if (!node.children.length) {
        emptyCategory[node.id] = node;
      }
    }
    // 书签
    if (node.url) {
      allBookmarks.add(node);
      if (map.has(node.url)) {
        if (!repeatBookmarks[node.url]) {
          repeatBookmarks[node.url] = new Set();
        }
        repeatBookmarks[node.url].add(map.get(node.url));
        repeatBookmarks[node.url].add(node);
      } else {
        map.set(node.url, node);
      }
      if (!map2.has(node.title)) {
        map2.set(node.title, node);
      } else {
        if (!repeatBookmarks2[node.title]) {
          repeatBookmarks2[node.title] = new Set();
        }
        repeatBookmarks2[node.title].add(map2.get(node.title));
        repeatBookmarks2[node.title].add(node);
      }
    }
  }
  return { allBookmarks, repeatBookmarks, category, emptyCategory, repeatBookmarks2 };
}

(async () => {
  const bookmarkTreeNodes = await getTree();
  const { allBookmarks, repeatBookmarks, category, emptyCategory, repeatBookmarks2 } =
    traverse(bookmarkTreeNodes);

  let fragment = '';
  const output = document.getElementById('output');
  // 重复书签
  for (let url in repeatBookmarks) {
    for (let node of repeatBookmarks[url]) {
      let parentId = node.parentId;
      let str = node.title;
      while (parentId !== '0') {
        let parent = category[parentId];
        str = parent.title + ' > ' + str;
        parentId = parent.parentId;
      }

      fragment = fragment + `<li>${str}</li>`;
    }
  }
  output.insertAdjacentHTML('beforeend', '<h2>重复书签</h2>');
  output.insertAdjacentHTML(
    'beforeend',
    fragment ? `<ul>${fragment}</ul>` : '<div>没有重复的书签</div>'
  );
  // 重复书签（网页标题一样的书签）
  fragment = '';
  for (let url in repeatBookmarks2) {
    for (let node of repeatBookmarks2[url]) {
      let parentId = node.parentId;
      let str = node.title;
      while (parentId !== '0') {
        let parent = category[parentId];
        str = parent.title + ' > ' + str;
        parentId = parent.parentId;
      }

      fragment = fragment + `<li>${str}</li>`;
    }
  }
  output.insertAdjacentHTML('beforeend', '<h2>重复书签（网页标题一样的书签）</h2>');
  output.insertAdjacentHTML(
    'beforeend',
    fragment ? `<ul>${fragment}</ul>` : '<div>没有重复的书签</div>'
  );

  // 所有分类
  fragment = '';
  for (let id in category) {
    let node = category[id];
    let str = node.title;
    while (node.parentId && node.parentId !== '0') {
      let parent = category[node.parentId];
      str = parent.title + ' > ' + str;
      node = parent;
    }
    if (str) {
      fragment = fragment + `<li>${str}</li>`;
    }
  }
  output.insertAdjacentHTML('beforeend', '<h2>所有分类</h2>');
  output.insertAdjacentHTML(
    'beforeend',
    fragment ? `<ul>${fragment}</ul>` : '<div>没有分类</div>'
  );

  // 移除所有空分类
  fragment = '';
  for (let id in emptyCategory) {
    let node = emptyCategory[id];
    let str = node.title;
    while (node.parentId && node.parentId !== '0') {
      let parent = category[node.parentId];
      str = parent.title + ' > ' + str;
      node = parent;
    }
    fragment = fragment + `<li>${str}</li>`;
    chrome.bookmarks.remove(id);
  }
  output.insertAdjacentHTML('beforeend', '<h2>移除所有空分类</h2>');
  output.insertAdjacentHTML(
    'beforeend',
    fragment ? `<ul>${fragment}</ul>` : '<div>没有空的分类</div>'
  );
})();
